<?php

/**
 * Created by PhpStorm.
 * User: liuxiu
 * Date: 2022/7/14
 * Time: 18:32
 */

namespace business\elasticsearch\services;

use business\elasticsearch\models\BigDataRadarProjectModel;

class BigDataRadarProjectService
{
    public function subscript(
        $keyword,
        $landUsageLabel,
        $projectLabel,
        $fitmentFeeLabel,
        $startTime,
        $endTime,
        $isPriceGtAvg,
        $provinceCode,
        $cityCode,
        $areaCode,
        $page,
        $pageSize
    )
    {
        $condition = $this->subscriptConditionV2(
            $keyword,
            $landUsageLabel,
            $projectLabel,
            $fitmentFeeLabel,
            $startTime,
            $endTime,
            $isPriceGtAvg,
            $provinceCode,
            $cityCode,
            $areaCode
        );

        $query = BigDataRadarProjectModel::find()
            ->query($condition);

        $query->orderBy(['is_new' => SORT_DESC, "_score" => SORT_DESC]);

        $total = $query->count();

        //分页处理
        $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        $data = $query->asArray()->all();

        $result = ['total' => $total, 'list' => []];
        foreach ($data as $dv) {
            $tmp = $dv['_source'];
            if (!empty($dv['highlight'])) {
                foreach ($dv['highlight'] as $key => $value) {
                    $tmp[$key . 'HL'] = isset($value[0]) ? $value[0] : '';
                }
            }
            $result['list'][] = $tmp;
        }

        return $result;
    }

    public function subscriptConditionV2(
        $keyword = [],
        $landUsageLabel = [],
        $projectLabel = [],
        $fitmentFeeLabel = [],
        $startTime = '',
        $endTime = '',
        $isPriceGtAvg = [],
        $provinceCode = [],
        $cityCode = [],
        $areaCode = []
    ): array
    {
        //是否高端项目 and 省市地区匹配成功 and
        // (
        //      ( 近一年有拿地 and ((未设置订阅土地类型) or (设置了土地类型且有匹配上的)) and 土地标题匹配关键词)
        //      or ( 近一年有在建 and ((未设置在建类型) or (设置了在建类型且有匹配上的)) and 在建标题匹配关键词)
        //      or ( 近一年有在售 and ((未设置在售类型) or (设置了在售类型且有匹配上的)) and 在售标题匹配关键词)
        //)
        $slop = !empty(\Yii::$app->params['CommonDataDeveloperSlop']) ? \Yii::$app->params['CommonDataDeveloperSlop'] : 2;
        $query = [];
        $must = [];
        $query['function_score']['query']['bool']['must'] = &$must;

        //是否高端项目
        if (!empty($isPriceGtAvg)) {
            $must[] = ["terms" => ['is_price_gt_avg' => $isPriceGtAvg]];
        }

        //省市地区匹配成功
        if (!empty($areaCode)) {
            $areaShould = [
                0 => ['terms' => ['province_code' => $areaCode]],
                1 => ['terms' => ['city_code' => $areaCode]],
            ];
            $must[] = ["bool" => ["should" => $areaShould]];
        }

        if (!empty($provinceCode)) {
            $must[] = ["terms" => ['province_code' => $provinceCode]];
        }

        if (!empty($cityCode)) {
            $must[] = ["terms" => ['city_code' => $cityCode]];
        }

        $dateRange = [];
        if (!empty($startTime) && !empty($endTime)) {
            $dateRange['from'] = $startTime;
            $dateRange['to'] = $endTime;
        }

        //( 近一年有拿地 and ((未设置订阅土地类型) or (设置了土地类型且有匹配上的)) and 土地标题匹配关键词)
        $landCondition = [["term" => ["data_type" => "土地交易"]]];
        if (!empty($keyword)) {
            $keywordCondition = [];
            foreach ($keyword as $k) {
                $keywordCondition[] = [
                    'match_phrase' => ['land_title' => ["query" => $k, "boost" => 10, 'slop' => $slop]]
                ];
            }
            $landCondition[] = ["bool" => ["should" => $keywordCondition]];
//            $landCondition[] = [
//                'terms' => ['land_title' => $keyword]
//            ];
        }

        if (!empty($dateRange)) {
            $landCondition[] = [
                'range' => ['take_land_date' => $dateRange]
            ];
        }

        if (!empty($landUsageLabel)) {
            $nestedLandUsageQuery['bool']['filter']['terms']['land_usage_label_v2.label.keyword'] = $landUsageLabel;
            $landCondition[] = [
                "nested" => [
                    "path" => "land_usage_label_v2",
                    "query" => $nestedLandUsageQuery
                ]
            ];
        }

        //( 近一年有在建 and ((未设置在建类型) or (设置了在建类型且有匹配上的)) and 在建标题匹配关键词)
        $buildCondition = [["term" => ["data_type" => "在建项目"]]];
        if (!empty($keyword)) {
            $keywordCondition = [];
            foreach ($keyword as $k) {
                $keywordCondition[] = [
                    'match_phrase' => ['project_title' => ["query" => $k, "boost" => 10, 'slop' => $slop]]
                ];
            }
            $buildCondition[] = ["bool" => ["should" => $keywordCondition]];
//            $buildCondition[] = [
//                'terms' => ['project_title' => $keyword]
//            ];
        }

        if (!empty($projectLabel)) {
            $buildCondition[] = [
                'terms' => ['project_label' => $projectLabel]
            ];
        }

        if (!empty($dateRange)) {
            $buildCondition[] = [
                "bool" => [
                    "should" => [
                        ['range' => ['prj_approval_date' => $dateRange]],
                        ['range' => ['begin_date' => $dateRange]],
                        ['range' => ['end_date' => $dateRange]],
                        ['range' => ['contract_date' => $dateRange]],
                        ['range' => ['release_date' => $dateRange]],
                        ['range' => ['tender_result_date' => $dateRange]]
                    ]
                ]

            ];
        }

        //( 近一年有在售 and ((未设置在售类型) or (设置了在售类型且有匹配上的)) and 在售标题匹配关键词)
        $openingCondition = [["term" => ["data_type" => "开盘项目"]]];
        if (!empty($keyword)) {
            $keywordCondition = [];
            foreach ($keyword as $k) {
                $keywordCondition[] = [
                    'match_phrase' => ['project_title' => ["query" => $k, "boost" => 10, 'slop' => $slop]]
                ];
            }
            $openingCondition[] = ["bool" => ["should" => $keywordCondition]];
//            $openingCondition[] = [
//                'terms' => ['project_title' => $keyword]
//            ];
        }
        if (!empty($dateRange)) {
            $openingCondition[] = [
                'range' => ['opening_time' => $dateRange]
            ];
        }
        if (!empty($fitmentFeeLabel)) {
            $openingCondition[] = [
                'terms' => ['fitment_fee_label' => $fitmentFeeLabel]
            ];
        }

        $must[] = ["bool" => ["should" => [
            ["bool" => ["must" => $landCondition]],
            ["bool" => ["must" => $buildCondition]],
            ["bool" => ["must" => $openingCondition]]]]];
//        echo json_encode($query, 256);
//        exit;
        return $query;
    }

    public function subscriptCondition(
        $keyword = [],
        $landUsageLabel = [],
        $projectLabel = [],
        $fitmentFeeLabel = [],
        $startTime = '',
        $endTime = '',
        $isPriceGtAvg = [],
        $provinceCode = [],
        $cityCode = [],
        $areaCode = [],
        $dataType = []
    )
    {
        //是否高端项目 and
        // (
        //      ( 近一年有拿地 and 省市地区匹配成功 and ((未设置订阅土地类型) or (设置了土地类型且有匹配上的)) and 土地标题匹配关键词)
        //      or ( 近一年有在建 and 省市地区匹配成功 and ((未设置在建类型) or (设置了在建类型且有匹配上的)) and 在建标题匹配关键词)
        //      or ( 近一年有在售 and 省市地区匹配成功 and ((未设置在售类型) or (设置了在售类型且有匹配上的)) and 在售标题匹配关键词)
        //)
        $query = [];
        $slop = !empty(\Yii::$app->params['CommonDataDeveloperSlop']) ? \Yii::$app->params['CommonDataDeveloperSlop'] : 2;
        $must = [];
        $query['function_score']['query']['bool']['must'] = &$must;

        //项目关键词
        if (!empty($keyword)) {
            $keyShould = [];
            $must[] = ['bool' => ['should' => &$keyShould]];

            foreach ($keyword as $k) {

                $titleBool = [];
                $titleBool[] = [
                    'match_phrase' => ['land_title' => ["query" => $k, 'slop' => $slop]]
                ];
                $keyShould[] = ["bool" => ["must" => $titleBool]];

                $projectBool = [];
                $projectBool[] = [
                    'match_phrase' => ['project_title' => ["query" => $k, "boost" => 3, 'slop' => $slop]]
                ];
                $keyShould[] = ["bool" => ["must" => $projectBool]];

            }
        }

        /**
         *  8个时间是或的关系
         *
         * 'take_land_date'
         * 'opening_time'
         * 'prj_approval_date'
         * 'begin_date'
         * 'end_date'
         * 'contract_date'
         * 'release_date'
         * 'tender_result_date'
         *
         */

        if (!empty($startTime) && !empty($endTime)) {
            $timeShould = [];
            $must[] = ['bool' => ['should' => &$timeShould]];
            $dateRange = [];
            $dateRange['from'] = $startTime;
            $dateRange['to'] = $endTime;

            //take_land_date
            $takeLandDateBool = [];
            $takeLandDateBool[] = [
                'range' => ['take_land_date' => $dateRange]
            ];
            $timeShould[] = ["bool" => ["must" => $takeLandDateBool]];

            //opening_time
            $openingTimeBool = [];
            $openingTimeBool[] = [
                'range' => ['opening_time' => $dateRange]
            ];
            $timeShould[] = ["bool" => ["must" => $openingTimeBool]];

            //prj_approval_date
            $prjApprovalDateBool = [];
            $prjApprovalDateBool[] = [
                'range' => ['prj_approval_date' => $dateRange]
            ];
            $timeShould[] = ["bool" => ["must" => $prjApprovalDateBool]];

            //begin_date
            $beginDateBool = [];
            $beginDateBool[] = [
                'range' => ['begin_date' => $dateRange]
            ];
            $timeShould[] = ["bool" => ["must" => $beginDateBool]];

            //end_date
            $endDateBool = [];
            $endDateBool[] = [
                'range' => ['end_date' => $dateRange]
            ];
            $timeShould[] = ["bool" => ["must" => $endDateBool]];

            //contract_date
            $contractDateBool = [];
            $contractDateBool[] = [
                'range' => ['contract_date' => $dateRange]
            ];
            $timeShould[] = ["bool" => ["must" => $contractDateBool]];

            //release_date
            $releaseDateBool = [];
            $releaseDateBool[] = [
                'range' => ['release_date' => $dateRange]
            ];
            $timeShould[] = ["bool" => ["must" => $releaseDateBool]];

            //tender_result_date
            $tenderResultDateBool = [];
            $tenderResultDateBool[] = [
                'range' => ['tender_result_date' => $dateRange]
            ];
            $timeShould[] = ["bool" => ["must" => $tenderResultDateBool]];

        }

        //should 是或的关系,$landUsageLabel || $projectLabel || $fitmentFeeLabel
        $should = [];
        $must[] = ['bool' => ['should' => &$should]];

        //(${land_usage_label} = '' and land_usage_label_v2 is not null) or land_usage_label_v2 in (${land_usage_label})
        $landBool = [];
        if (!empty($landUsageLabel)) {
            /*$landBool[] = [
               'terms' => ['land_usage_label_v2' => $landUsageLabel]
           ];*/
            $nestedLandUsageQuery['bool']['filter']['terms']['land_usage_label_v2.label.keyword'] = $landUsageLabel;
            $landBool = [
                'nested' => [
                    'path' => 'land_usage_label_v2',
                    'query' => $nestedLandUsageQuery
                ]
            ];
        } else {
            $landBool[] = [
                'bool' => ['must' => [
                    0 => ['term' => ['data_type' => '土地交易']]
                ]]
            ];
        }
        $should[] = ["bool" => ["should" => $landBool]];

        //(${project_label} = '' and project_label is not null) or project_label in (${project_label})
        $projectBool = [];
        if (!empty($projectLabel)) {
            $projectBool[] = [
                'terms' => ['project_label' => $projectLabel]
            ];
        } else {
            $projectBool[] = [
                'bool' => ['must' => [
                    0 => ['term' => ['data_type' => '在建项目']]
                ]]
            ];
        }

        $should[] = ["bool" => ["should" => $projectBool]];

        // (${fitment_fee_label} = '' and fitment_fee_label is not null) or fitment_fee_label in (${fitment_fee_label})
        $fitmentFeeBool = [];
        if (!empty($fitmentFeeLabel)) {
            $fitmentFeeBool[] = [
                'terms' => ['fitment_fee_label' => $fitmentFeeLabel]
            ];
        } else {
            $fitmentFeeBool[] = [
                'bool' => ['must' => [
                    0 => ['term' => ['data_type' => '开盘项目']]
                ]]
            ];
        }
        $should[] = ["bool" => ["should" => $fitmentFeeBool]];

        $areaShould = [];
        if (!empty($areaCode)) {
            $areaShould = [
                0 => ['terms' => ['province_code' => $areaCode]],
                1 => ['terms' => ['city_code' => $areaCode]],
            ];
        }
        $must[] = ["bool" => ["should" => $areaShould]];


        //且的关系
        if (!empty($provinceCode)) {
            $must[] = ["terms" => ['province_code' => $provinceCode]];
        }

        if (!empty($cityCode)) {
            $must[] = ["terms" => ['city_code' => $cityCode]];
        }

        if (!empty($isPriceGtAvg)) {
            $must[] = ["terms" => ['is_price_gt_avg' => $isPriceGtAvg]];
        }

        if (!empty($dataType)) {
            $must[] = ["terms" => ['data_type' => $dataType]];
        }

        return $query;
    }
}
